# Copyright 2009 Lee Harr
#
# This file is part of Acromania.
#
# Acromania is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Acromania is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Acromania.  If not, see <http://www.gnu.org/licenses/>.


try:
    import conf
except ImportError:
    import util
    util.makeconf()

    import amdb
    amdb.dbcheck()

    raise SystemExit

from twisted.internet import protocol
from twisted.application import service, internet
from twisted.internet import reactor

from amserver import GameServer
from amprotocol import AM
from amircprotocol import AMIRC
import amdb


if not amdb.dbcheckver():
    print 'Database version mismatch. Server not started.'
    print 'Try upgrading database with amdb.py'
    raise SystemExit


gameserver = GameServer()


class AMServer(internet.TCPServer):
    'Main Server class.'
    pass

class AMIRCBotFactory(protocol.ClientFactory):
    """A factory for AMIRCBots.

    A new protocol instance will be created each time we connect to the server.
    """

    # the class of the protocol to build when new connection is made
    protocol = AMIRC
    gameserver = gameserver

    def __init__(self):
        self.channel = conf.channels[0]

    def clientConnectionLost(self, connector, reason):
        """If we get disconnected, reconnect to server."""
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "connection failed:", reason
        reactor.stop()


application = service.Application('acromania_server')


if conf.standalone_enabled:
    factory = protocol.ServerFactory()
    AM.gameserver = gameserver
    AM.factory = factory
    factory.protocol = AM
    server = AMServer(conf.standalone_port, factory, 1, '127.0.0.1')
    server.setServiceParent(application)

if conf.ircbot_enabled:
    amircbotfactory = AMIRCBotFactory()
    reactor.connectTCP(conf.irc_server, 6667, amircbotfactory)


reactor.callLater(3, gameserver.trickle_send)


amdb.dbopen()
reactor.addSystemEventTrigger("after", "shutdown", amdb.dbclose)
